<template>
  <div class="echart-container">
    <div class="chart" ref="chartRef"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick, watch } from "vue";
import * as echarts from "echarts";
import { usePlcStore } from "@/stores/plc";
import dayjs from "dayjs";

// 使用 store
const plcStore = usePlcStore();
const loadTag = ref(true);

// 定义图表实例
const chartRef = ref(null);
let chartInstance = null;
let resizeObserver = null;
const threshold = ref(3);

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return;

  // 如果已有实例，先销毁
  if (chartInstance) {
    chartInstance.dispose();
  }

  chartInstance = echarts.init(chartRef.value);

  // 图表配置
  const option = {
    backgroundColor: "",
    toolbox: {
      iconStyle: {
        borderColor: "#ffffff", // 设置toolbox图标为白色
      },
      emphasis: {
        iconStyle: {
          borderColor: "#409EFF", // 鼠标悬停时的颜色
        },
      },
      feature: {
        dataZoom: {
          yAxisIndex: "none",
          title: {
            zoom: "区域缩放",
            back: "区域缩放还原",
          },
        },
        dataView: {
          title: "数据视图",
          readOnly: false,
        },
        restore: {
          title: "还原",
        },
        saveAsImage: {
          title: "保存为图片",
        },
      },
    },
    tooltip: {
      trigger: "axis",
      formatter: (params) => {
        // 获取首个参数的时间（所有系列在相同时间点）
        const timestamp = params[0].value[0];
        // 格式化时间（HH:mm:ss格式）
        const timeStr = dayjs(timestamp).format("HH:mm:ss");

        let result = `<div style="text-align: left; margin-bottom: 5px">时间: ${timeStr}</div>`;

        params.forEach((param) => {
          // 注意：param.value 是数组 [时间戳, 数值]
          const value = param.value[1] !== undefined ? param.value[1] : "0"; // 获取数值部分

          if (param.seriesName === "局放值") {
            result += `${param.marker} ${param.seriesName}: ${value} pC<br/>`;
          } else if (param.seriesName === "电压值") {
            result += `${param.marker} ${param.seriesName}: ${value} kV<br/>`;
          }
        });
        return result;
      },
    },

    grid: {
      top: "15%",
      left: "3%",
      right: "4%",
      bottom: "10%",
      containLabel: true,
    },
    xAxis: {
      type: "time", // 设置X轴为时间类型
      axisLabel: {
        color: "#ffffff", // X轴标签颜色设为白色
        formatter: function (value) {
          // 使用day.js格式化时间为"HH:mm:ss"格式
          return dayjs(value).format("mm:ss");
        },
        interval: "auto",
      },
    },
    yAxis: [
      {
        type: "value",
        name: "局放值 (pC)",
        axisLine: {
          show: true,
          lineStyle: {
            color: "#ffffff",
          },
        },
        axisLabel: {
          formatter: function (value) {
            // 当值等于阈值时，不显示该刻度
            return value === threshold.value ? "" : value;
          },
        },
      },
      {
        type: "value",
        name: "电压值 (kV)",
        position: "right",
        axisLine: {
          show: true,
          lineStyle: {
            color: "#ffffff",
          },
        },
      },
    ],
    dataZoom: [
      {
        type: "inside",
        xAxisIndex: [0],
        start: 0,
        end: 100, // 显示全部数据
      },
      {
        type: "slider",
        xAxisIndex: [0],
        start: 0,
        end: 100, // 显示全部数据
        bottom: 10,
        height: 20,
      },
    ],
    series: [
      {
        name: "电压值",
        type: "line",
        yAxisIndex: 0,
        data: [],
        smooth: true,
        lineStyle: { width: 3, color: "#5470C6" },
        symbol: "none",
      },
      {
        name: "局放值",
        type: "line",
        yAxisIndex: 1,
        data: [],
        smooth: true,
        lineStyle: { width: 3, color: "#91CC75" },
        symbol: "none",
      },
    ],
  };

  chartInstance.setOption(option);
};

const resizeChart = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};

onMounted(() => {
  nextTick(() => {
    // 使用 ResizeObserver 监听容器尺寸变化
    resizeObserver = new ResizeObserver(resizeChart);

    if (chartRef.value) {
      resizeObserver.observe(chartRef.value);
    }

    // 添加窗口大小变化监听
    window.addEventListener("resize", resizeChart);

    // 初始调整大小
    setTimeout(resizeChart, 100);
  });
});

onBeforeUnmount(() => {
  if (resizeObserver && chartRef.value) {
    resizeObserver.unobserve(chartRef.value);
  }
  window.removeEventListener("resize", resizeChart);
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
  if (dataUpdateTimer) {
    clearInterval(dataUpdateTimer);
    dataUpdateTimer = null;
  }
});

watch(
  () => plcStore.isConnected,
  (isConnected) => {
    if (isConnected) {
      loadTag.value = false;
      initChart();
    } else {
      loadTag.value = true;
    }
  }
);

// 监听数据变化并更新图表
watch(
  () => [plcStore.voltageArray, plcStore.partialDischargeArray],
  ([voltageData, dischargeData]) => {
    if (chartInstance) {
      chartInstance.setOption({
        series: [
          {
            name: "电压值",
            data: [...voltageData],
          },
          {
            name: "局放值",
            data: [...dischargeData],
          },
        ],
      });
    }
  },
  { deep: true }
);
</script>

<style lang="less" scoped>
.echart-container {
  height: 100%;
  width: 100%;
  padding: 16px;
  display: flex;
  flex-direction: column;
  border-radius: 5px;

  .chart-title {
    font-size: 20px;
    color: #fff;
    font-weight: 600;
    margin-top: 15px;
    text-align: center;
  }

  .chart {
    flex: 1;
    width: 100%;
    min-height: 300px;
  }
}
</style>